package com.elight.sys.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.elight.entity.ZTreeNode;
import com.elight.sys.dao.SysPermissionDao;
import com.elight.sys.dao.SysRoleAuthorizeDao;
import com.elight.sys.entity.SysPermission;
import com.elight.sys.entity.SysRoleAuthorize;
import com.elight.sys.service.RoleAuthorizeService;
import com.elight.utils.OperatorProvider;

@Service
public class RoleAuthorizeServiceImp implements RoleAuthorizeService {
	@Autowired
	private SysRoleAuthorizeDao roleAuthorizeDao;
	@Autowired
	private SysPermissionDao permissionDao;

	@Override
	@Transactional
	public void authorize(HttpSession session, String roleId, String[] perIdArray) {
		// 角色原有的授权信息。
		List<SysRoleAuthorize> listOldPers = roleAuthorizeDao.getList(roleId);
		for (SysRoleAuthorize item : listOldPers) {
			roleAuthorizeDao.delete(item.getId());
		}
		// 新增新的权限
		for (String moduleId : perIdArray) {
			SysRoleAuthorize item = new SysRoleAuthorize();
			item.setId(UUID.randomUUID().toString().replace("-", ""));
			item.setRoleId(roleId);
			item.setModuleId(moduleId);
			item.setCreateTime(new Date());
			item.setCreateUser(OperatorProvider.getCurrent(session).getAccount());
			roleAuthorizeDao.insert(item);
		}
	}

	@Override
	public List<ZTreeNode> getZTreeNode(String roleId) {
		List<SysRoleAuthorize> sysRoleAuthorizeList = roleAuthorizeDao.getList(roleId);
		List<String> listPerIds = new ArrayList<String>();
		for (SysRoleAuthorize item : sysRoleAuthorizeList) {
			if (!listPerIds.contains(item.getModuleId()))
				listPerIds.add(item.getModuleId());
		}
		List<SysPermission> listAllPers = permissionDao.getPermissionList();
		List<ZTreeNode> result = new ArrayList<ZTreeNode>();
		for (SysPermission item : listAllPers) {
			ZTreeNode model = new ZTreeNode();
			model.setChecked(listPerIds.contains(item.getId()) ? true : false);
			model.setId(item.getId());
			model.setpId(item.getParentId());
			model.setName(item.getName());
			model.setOpen(true);
			result.add(model);
		}
		return result;
	}

}
